package com.xk.androiddemo;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.kongzue.dialogx.dialogs.PopTip;

import com.xk.androiddemo.database.AppDatabase;
import com.xk.androiddemo.database.UserBean;

public class LoginActivity extends AppCompatActivity {
    private TextInputEditText tid,tid2;
    private Button button,register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        tid = findViewById(R.id.materialAutoCompleteTextView);
        tid2 = findViewById(R.id.materialAutoCompleteTextView2);
        button = findViewById(R.id.logIn);
        register = findViewById(R.id.register);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s1 = tid.getText().toString();
                String s2 = tid2.getText().toString();
                if(TextUtils.isEmpty(s1)||TextUtils.isEmpty(s2)){
                    PopTip.show("请输入用户名和密码");
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        UserBean userBean = AppDatabase.getDatabase(LoginActivity.this).
                                UserDao().getUserByUsername(s1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (userBean == null) {
                                    PopTip.show("用户名不存在");
                                    return;
                                }
                                if(userBean.getPwd().equals(s2)){
                                    Intent intent =new Intent(LoginActivity.this,MainActivity.class);
                                    App.userBean = userBean;
                                    startActivity(intent);
                                    finish();
                                }else{
                                    PopTip.show("密码错误");
                                    return;
                                }
                            }
                        });
                    }
                }).start();
            }
        });
    }
}